<template>
	<view class="container">
		<!-- 加载动画 -->
		<uni-load-more v-if="loading" status="loading" iconType="circle"></uni-load-more>

		<!-- 日历区域 -->
		<uni-calendar :lunar="false" @change="handleDateChange" :date="currentDate" :selected="selectedDates"
			:showMonth="false"></uni-calendar>

		<!-- 值班管理区域 -->
		<view class="duty-section">
			<!-- 分类选项卡 -->
			<view class="tabs">
				<view v-for="(tab, index) in tabs" :key="index" :class="['tab', activeTab === index ? 'active' : '']"
					@click="switchTab(index)">
					{{ tab.name }}（{{ tab.selected }}/{{ tab.total }}）
				</view>
			</view>

			<!-- 滑动切换区域 -->
			<swiper :current="activeTab" @change="onSwiperChange" :style="{height: swiperHeight + 'px'}">
				<!-- 带班领导 -->
				<swiper-item>
					<scroll-view scroll-y :style="{height: swiperHeight + 'px'}">
						<view class="staff-grid">
							<button v-for="staff in currentLeaders" :key="staff.id"
								:class="['staff-btn', staff.selected ? 'selected' : '']"
								@click="toggleSelection(staff)">
								{{ staff.name }}
							</button>
						</view>
					</scroll-view>
				</swiper-item>

				<!-- 值班人员 -->
				<swiper-item>
					<scroll-view scroll-y :style="{height: swiperHeight + 'px'}">
						<view class="staff-grid">
							<button v-for="staff in currentStaff" :key="staff.id"
								:class="['staff-btn', staff.selected ? 'selected' : '']"
								@click="toggleSelection(staff)">
								{{ staff.name }}
							</button>
						</view>
					</scroll-view>
				</swiper-item>
			</swiper>
		</view>

		<!-- 提交按钮 -->
		<view class="footer">
			<button class="submit-btn" @click="handleSubmit">提交值班安排</button>
		</view>
	</view>
</template>

<script>
	// 模拟数据生成方法
	const generateLeaders = () => {
		return Array.from({
			length: 10
		}, (_, i) => ({
			id: `L${i + 1}`,
			name: `领导${i + 1}`,
			type: 'leader',
			selected: false
		}))
	}

	const generateStaff = () => {
		return Array.from({
			length: 20
		}, (_, i) => ({
			id: `S${i + 1}`,
			name: `员工${i + 1}`,
			type: 'staff',
			selected: false
		}))
	}

	export default {
		data() {
			return {
				loading: false,
				activeTab: 0,
				swiperHeight: 300,
				currentDate: '',
				scheduleData: {},
				tabs: [{
						name: '带班领导',
						type: 'leader',
						selected: 0,
						total: 0
					},
					{
						name: '值班人员',
						type: 'staff',
						selected: 0,
						total: 0
					}
				]
			}
		},
		computed: {
			currentLeaders() {
				return this.getCurrentStaff('leader')
			},
			currentStaff() {
				return this.getCurrentStaff('staff')
			},
			// 修改后的选中日期计算
			selectedDates() {
				return Object.keys(this.scheduleData)
					.filter(date => {
						const data = this.scheduleData[date]
						return (
							data.leader.some(l => l.selected) ||
							data.staff.some(s => s.selected)
						)
					})
					.map(date => ({
						date: date,
						info: '值班'
					}))
			}
		},
		created() {
			this.initData()
		},
		mounted() {
			this.calculateSwiperHeight()
		},
		methods: {
			initData() {
				const today = this.getDateString(new Date())
				this.currentDate = today
				this.ensureDateData(today)
			},

			ensureDateData(date) {
				if (!this.scheduleData[date]) {
					this.$set(this.scheduleData, date, {
						leader: generateLeaders(),
						staff: generateStaff(),
						lastModified: null
					})
					this.updateTabStats()
				}
			},

			getCurrentStaff(type) {
				this.ensureDateData(this.currentDate)
				return this.scheduleData[this.currentDate][type]
			},

			handleDateChange(e) {
				const selectedDate = this.getDateString(new Date(e.fulldate))
				this.currentDate = selectedDate
				this.ensureDateData(selectedDate)
				this.updateTabStats()
			},

			toggleSelection(staff) {
				const staffType = staff.type
				const staffList = this.scheduleData[this.currentDate][staffType]
				const index = staffList.findIndex(item => item.id === staff.id)
				staffList[index].selected = !staffList[index].selected
				this.updateTabStats()
			},

			updateTabStats() {
				this.tabs = this.tabs.map(tab => {
					const list = this.scheduleData[this.currentDate][tab.type]
					return {
						...tab,
						selected: list.filter(item => item.selected).length,
						total: list.length
					}
				})
			},

			handleSubmit() {
				const selectedLeaders = this.currentLeaders.filter(item => item.selected)
				const selectedStaff = this.currentStaff.filter(item => item.selected)

				uni.showModal({
					title: '提交确认',
					content: `确定提交 ${this.currentDate} 的值班安排？
已选领导：${selectedLeaders.length}人
已选员工：${selectedStaff.length}人`,
					success: (res) => {
						if (res.confirm) {
							// //console.log('提交数据：', {
							// 	date: this.currentDate,
							// 	leaders: selectedLeaders,
							// 	staff: selectedStaff
							// })
							this.scheduleData[this.currentDate].lastModified = new Date().toISOString()
							uni.showToast({
								title: '提交成功',
								icon: 'success'
							})
						}
					}
				})
			},

			getDateString(date) {
				const year = date.getFullYear()
				const month = String(date.getMonth() + 1).padStart(2, '0')
				const day = String(date.getDate()).padStart(2, '0')
				return `${year}-${month}-${day}`
			},

			switchTab(index) {
				this.activeTab = index
			},

			onSwiperChange(e) {
				this.activeTab = e.detail.current
			},

			calculateSwiperHeight() {
				const query = uni.createSelectorQuery().in(this)
				query.select('.duty-section').boundingClientRect(data => {
					this.swiperHeight = data.height - 50
				}).exec()
			}
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		height: 100vh;
		display: flex;
		flex-direction: column;
		background-color: #f8f8f8;
	}

	.duty-section {
		flex: 1;
		padding: 20rpx;
		background-color: #fff;
		box-shadow: 0 -4rpx 16rpx rgba(0, 0, 0, 0.05);
	}

	.tabs {
		display: flex;
		border-bottom: 2rpx solid #eee;
		background-color: #fff;
		position: relative;
		z-index: 10;
	}

	.tab {
		flex: 1;
		text-align: center;
		padding: 24rpx 0;
		font-size: 28rpx;
		color: #666;
		transition: all 0.3s;

		&.active {
			color: #007AFF;
			font-weight: 500;
			position: relative;

			&::after {
				content: '';
				position: absolute;
				bottom: 0;
				left: 50%;
				transform: translateX(-50%);
				width: 80rpx;
				height: 4rpx;
				background-color: #007AFF;
			}
		}
	}

	.staff-grid {
		display: flex;
		flex-wrap: wrap;
		padding: 20rpx;
		gap: 20rpx;
	}

	.staff-btn {
		width: 200rpx;
		height: 80rpx;
		line-height: 80rpx;
		margin: 0;
		padding: 0;
		border-radius: 12rpx;
		background-color: #f5f5f5;
		color: #333;
		font-size: 28rpx;
		transition: all 0.2s;
		border: none;

		&::after {
			border: none;
		}

		&.selected {
			background-color: #007AFF;
			color: #fff;
			transform: scale(0.98);
		}
	}

	.footer {
		padding: 30rpx;
		background: #fff;
		box-shadow: 0 -4rpx 16rpx rgba(0, 0, 0, 0.05);
	}

	.submit-btn {
		background: linear-gradient(135deg, #007AFF, #0063CC);
		color: #fff;
		border-radius: 50rpx;
		height: 80rpx;
		line-height: 80rpx;
		font-size: 32rpx;
		border: none;

		&::after {
			border: none;
		}

		&:active {
			opacity: 0.9;
		}
	}

	/* 新增日历选中样式 */
	::v-deep .uni-calendar__date--selected .uni-calendar__date-text {
		color: #fff !important;
		font-size: 24rpx !important;
	}

	::v-deep .uni-calendar__date--selected .uni-calendar__date-c {
		&::after {
			content: '值班';
			position: absolute;
			bottom: 10rpx;
			left: 50%;
			transform: translateX(-50%);
			font-size: 20rpx;
			color: #fff;
		}
	}
</style>